package com.gpt.article.controller;

import java.awt.*;
import java.io.File;
import java.util.*;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import chatgpt.ChatGPT;
import cn.hutool.json.JSONUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelWriter;
import cn.hutool.poi.excel.StyleSet;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.deepoove.poi.data.style.CellStyle;
import com.google.gson.JsonObject;
import com.gpt.article.domain.GptTopicTitle;
import com.gpt.article.service.impl.taskHandle.testTask.ClassTaskTest;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.framework.config.ServerConfig;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.gpt.article.domain.TxtClassify;
import com.gpt.article.service.ITxtClassifyService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 内容分类Controller
 * 
 * @author zhuzi
 * @date 2023-12-14
 */
@RestController
@RequestMapping("/article/classify")
public class TxtClassifyController extends BaseController
{
    @Autowired
    private ITxtClassifyService txtClassifyService;
    @Autowired
    private ServerConfig serverConfig;
    /**
     * 查询内容分类列表
     */
    @PreAuthorize("@ss.hasPermi('article:classify:list')")
    @GetMapping("/list")
    public TableDataInfo list(TxtClassify txtClassify)
    {
        startPage();
        List<TxtClassify> list = txtClassifyService.selectTxtClassifyList(txtClassify);
        return getDataTable(list);
    }

    /**
     * 导出内容分类列表
     */
    @PreAuthorize("@ss.hasPermi('article:classify:export')")
    @Log(title = "内容分类", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TxtClassify txtClassify)
    {
        List<TxtClassify> list = txtClassifyService.selectTxtClassifyList(txtClassify);
        ExcelUtil<TxtClassify> util = new ExcelUtil<TxtClassify>(TxtClassify.class);
        util.exportExcel(response, list, "内容分类数据");
    }

    /**
     * 获取内容分类详细信息
     */
    @PreAuthorize("@ss.hasPermi('article:classify:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(txtClassifyService.selectTxtClassifyById(id));
    }

    /**
     * 新增内容分类
     */
    @PreAuthorize("@ss.hasPermi('article:classify:add')")
    @Log(title = "内容分类", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TxtClassify txtClassify)
    {
        return toAjax(txtClassifyService.insertTxtClassify(txtClassify));
    }

    /**
     * 修改内容分类
     */
    @PreAuthorize("@ss.hasPermi('article:classify:edit')")
    @Log(title = "内容分类", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TxtClassify txtClassify)
    {
        return toAjax(txtClassifyService.updateTxtClassify(txtClassify));
    }

    /**
     * 删除内容分类
     */
    @PreAuthorize("@ss.hasPermi('article:classify:remove')")
    @Log(title = "内容分类", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(txtClassifyService.deleteTxtClassifyByIds(ids));
    }

//    public static void main(String[] args) {
//        String ep = "d:/test.xlsx";
//        String lawNamePath = "E:\\git-test\\class_task\\lawyer_name.xlsx";
//
//        File excelFile = new File(ep);
//        ExcelReader reader = cn.hutool.poi.excel.ExcelUtil.getReader(excelFile);
//        List<Map<String, Object>> maps = reader.readAll();
//
//        File lawFile = new File(lawNamePath);
//        ExcelReader lawReader = cn.hutool.poi.excel.ExcelUtil.getReader(lawFile);
//        List<Map<String, Object>> lawnamemaps = lawReader.readAll();
//        List<String> lawNames = new ArrayList<String>();
//        for(Map<String, Object> lmap:lawnamemaps){
//            Set<String> set = lmap.keySet();
//            for(String key:set){
////                System.out.println(key+"-->"+map.get(key));
//                String name  =String.valueOf( lmap.get(key));
//                lawNames.add(name);
//                break;
//            }
//        }
//        System.out.println(lawNames.contains("黄亚玲2"));
//    }




    public static void main(String[] args) {

        String ep = "d:/test.xlsx";
        String lawNamePath = "E:\\git-test\\class_task\\lawyer_name.xlsx";

        File excelFile = new File(ep);
        ExcelReader reader = cn.hutool.poi.excel.ExcelUtil.getReader(excelFile);
        List<Map<String, Object>> maps = reader.readAll();

        File lawFile = new File(lawNamePath);
        ExcelReader lawReader = cn.hutool.poi.excel.ExcelUtil.getReader(lawFile);
        List<Map<String, Object>> lawnamemaps = lawReader.readAll();
        List<String> lawNames = new ArrayList<String>();
        for(Map<String, Object> lmap:lawnamemaps){
            Set<String> set = lmap.keySet();
            for(String key:set){
//                System.out.println(key+"-->"+map.get(key));
                String name  =String.valueOf( lmap.get(key));
                lawNames.add(name);
                break;
            }
        }

        String  userid = "";
        String  screen_name = "";
        String  verified_reason = "";
        String  description = "";
        String  user_name = "";
        String  law_firms  = "";
        String is_match = "";
        ArrayList<Map<String, Object>> rows = new ArrayList<Map<String, Object>>();
        Map<String, Object> row1 = null;
        for(Map map:maps){
            userid = String.valueOf(map.get("userid"));
            screen_name = String.valueOf(map.get("screen_name"));
            verified_reason = String.valueOf(map.get("verified_reason"));
            description = String.valueOf(map.get("description"));
            user_name = String.valueOf(map.get("user_name"));
            law_firms = String.valueOf(map.get("law_firms"));
            boolean isHas = lawNames.contains(user_name);
            if(isHas){
                is_match = "是";
            }else{
                is_match = "否";
            }
            row1 = new LinkedHashMap<>();
            row1.put("userid",userid);
            row1.put("screen_name",screen_name);
            row1.put("verified_reason",verified_reason);
            row1.put("description",description);
            row1.put("user_name",user_name);
            row1.put("law_firms",law_firms);
            row1.put("is_match",is_match);
            rows.add(row1);
        }

        //创建excel
        ExcelWriter writer = cn.hutool.poi.excel.ExcelUtil.getWriter("d:/test2.xlsx");
// 一次性写出内容，使用默认样式，强制输出标题
        writer.write(rows, true);
// 关闭writer，释放内存
        writer.close();
        reader.close();
    }

    public static void main2(String[] args) {
        String ep = "E:\\git-test\\class_task\\微博.xlsx";
        File excelFile = new File(ep);
        ExcelReader reader = cn.hutool.poi.excel.ExcelUtil.getReader(excelFile);
        List<Map<String, Object>> maps = reader.readAll();


        String  userid = "";
        String  screen_name = "";
        String  verified_reason = "";
        String  description = "";
        String  user_name = "";
        String  law_firms  = "";
        Map<String, Object> row1 = null;
        ArrayList<Map<String, Object>> rows = new ArrayList<Map<String, Object>>();

        String prompts ="";
        ChatGPT chatGPT = null;
        String res = "";
        for(Map map:maps){
//            Set<String> set = map.keySet();
//            System.out.println(map);
            userid = String.valueOf(map.get("userid"));
            screen_name = String.valueOf(map.get("screen_name"));
            verified_reason = String.valueOf(map.get("verified_reason"));
            String sourceinfo = String.valueOf(map.get("sourceinfo"));
            JSONObject json = JSON.parseObject(sourceinfo);
            description = String.valueOf(json.get("description"));
//            System.out.println(description);
            row1 = new LinkedHashMap<>();
            row1.put("userid",userid);
            row1.put("screen_name",screen_name);
            row1.put("verified_reason",verified_reason);
            row1.put("description",description);

            prompts =  "提取下面内容中律师的名字和律师事务所全称，格式必须是：律师名字/律所名称，律师名字不要带律师两个字，如果其中一个没找到则该名称为无，直接告诉人名/律所全称（中间用/隔开） 即可，回答字数不能超过20个字。内容："
                    +screen_name+","+verified_reason+","+description;
            chatGPT = ChatGPT.builder()
                    .apiKey("sk-64zKz69svXDWdkfQA66d79C009F947F8A658E1Dd5292E2Ab")
                    .timeout(900)
//                .proxy(proxy)
                    .apiHost("https://hixtebrwfjyc.cloud.sealos.io/") //代理地址
                    .build()
                    .init();
            try {
                res = chatGPT.chat(prompts);
            }catch (Exception e){
                System.out.println(e.getMessage());
            }
            System.out.println("获取到信息："+res);
             String rs[] = res.split("/");
             if(rs.length>0){
                 user_name =rs[0];
             }
            if(rs.length>1){
                law_firms =rs[1];
            }
            row1.put("user_name",user_name);
            row1.put("law_firms",law_firms);


            rows.add(row1);
//            for(String key:set){
//                String title  =String.valueOf("~~~"+ map.get(key));
//                System.out.println(title);
//            }
//            if(a>10){
//                break;
//            }
//            a++;
        }

        //创建excel
        ExcelWriter writer = cn.hutool.poi.excel.ExcelUtil.getWriter("d:/test.xlsx");
// 一次性写出内容，使用默认样式，强制输出标题
        writer.write(rows, true);
// 关闭writer，释放内存
        writer.close();
        reader.close();

    }



    /**
     * 上传待分类内容
     * @param file
     * @return
     * @throws Exception
     */
    @Log(title = "上传待分类内容", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file) throws Exception {
//
        String operName = getUsername();
        // 上传文件路径
        String filePath = RuoYiConfig.getUploadPath();
        // 上传并返回新文件名称
        String fileName = FileUploadUtils.upload(filePath, file);
        String url = serverConfig.getUrl() + fileName;
        AjaxResult ajax = AjaxResult.success();
        ajax.put("url", url);
        ajax.put("fileName", fileName);
        ajax.put("newFileName", FileUtils.getName(fileName));
        ajax.put("originalFilename", file.getOriginalFilename());
        System.out.println(filePath + "/" + fileName);
        //解析文件
        System.out.println(filePath + "--");
        String tmpfilePath = filePath + fileName.replaceAll("/profile/upload", "");
        File excelFile = new File(tmpfilePath);
        ExcelReader reader = cn.hutool.poi.excel.ExcelUtil.getReader(excelFile);
        List<Map<String, Object>> maps = reader.readAll();
        TxtClassify txtClassify = null;
        for(Map map:maps){
            Set<String> set = map.keySet();
            for(String key:set){
//                System.out.println(key+"-->"+map.get(key));
                String title  =String.valueOf( map.get(key));

                txtClassify = new TxtClassify();
                txtClassify.setTxtContent(title);
                txtClassify.setTxtLength(title.trim().length());
                txtClassify.setStatus("0");
                txtClassify.setCreateBy(getUsername());
                txtClassifyService.insertTxtClassify(txtClassify);
                break;
            }
        }
        reader.close();
        new ClassTaskTest().importExl();
//        new ClassTaskTest().writeExcel();
//        new ClassTaskTest().checkClassNames();
        return success("成功");
    }



    /**
     * 生成内容分类
     * @param map
     * @return
     * @throws Exception
     */
    @Log(title = "生成内容分类", businessType = BusinessType.GEN)
//    @GetMapping("/startGen/{ids}")
//    public AjaxResult startGen(@PathVariable Long[] ids){
    @PostMapping("/startGen")
    public AjaxResult startGen(@RequestBody  Map<String,Object> map){
        String acc = SecurityUtils.getUsername();
        String idstr = String.valueOf(map.get("ids"));
        String idst[] =  idstr.split(",");
        Long[] ids = stringToLong(idst);

        txtClassifyService.genGptClassify(ids,acc,map);
//        new ClassTaskTest().importExl();
        return success(true);
    }




    /**
     * 全量（可指定数量）运行
     *
     * @param map
     *    参数条件
     */
    @Log(title = "执行全量（可指定数量）生成分类任务", businessType = BusinessType.GEN)
    @PostMapping("/tartGenAll")
    public AjaxResult tartGenAll(@RequestBody Map<String,Object> map)
    {
        TxtClassify txtClassify = new TxtClassify();
        BeanMap beanMap = BeanMap.create(txtClassify);
        beanMap.putAll(map);
        String acc = SecurityUtils.getUsername();
//        gptTopicTitleService.genManyTopic(txtClassify,acc);
        txtClassifyService.genManyGptClassify(txtClassify,acc,map);
        return success(true);
    }






    public Long[] stringToLong(String[] strings) {
        if (strings == null || strings.length < 1) {
            return null;
        }
        Long[] longs = new Long[strings.length];
        for (int i = 0; i < strings.length; i++) {
            String longidstr = strings[i].replaceAll("\\[","")
                    .replaceAll("\\]","").replaceAll(" ","").trim();
            Long str = Long.valueOf(longidstr);
            longs[i] = str;
        }
        return longs;
    }

}
